<script setup>
import { ref, reactive } from "vue";
import { closeToast, showLoadingToast, showFailToast } from 'vant';
import { login } from "@/api/userApi";
import { useRouter } from "vue-router";

const router = useRouter();
const submitData = reactive({
    loginname: "",
    password: "",
});

// 校验函数返回 true 表示校验通过，false 表示不通过
const validatePhone = (val) => /^1[3-9]\d{9}$/.test(val);

const validatePassword = (val) => {
    if (!val) return "密码不能为空";
    if (val.length < 8 || val.length > 20) return "密码长度需为8-20位";
    if (!/(?=.*[0-9])(?=.*[a-zA-Z])/.test(val)) return "密码需包含数字和字母";
    return ""; // 校验通过
};

const onFailed = async (data) => {
    let result = await login(data)
    if (result.code !== "200") return showFailToast(result.message);
    localStorage.setItem("mobileTerminalToken", result.data.token);
    localStorage.setItem("mobileTerminalUserId", result.data.userid);
    router.push("/");
};
</script>

<template>
    <div class="login">
        <div class="content">
            <h1>登录</h1>
            <van-form @submit="onFailed">
                <van-cell-group inset>
                    <!-- 通过 pattern 进行正则校验 -->
                    <van-field v-model="submitData.loginname" name="loginname" placeholder="请输入手机号"
                        :rules="[{ validator: validatePhone, message: '请输入正确的手机号' }]" />
                    <!-- 通过 validator 进行函数校验 -->
                    <van-field v-model="submitData.password" name="password" placeholder="请输入密码" :rules="[{
                        validator: (val) => !validatePassword(val),
                        message: validatePassword(submitData.password),
                    }]" />
                    <!-- 通过 validator 返回错误提示 -->
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button round block type="primary" native-type="submit">
                        登录
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>

<style scoped>
.login {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
}

.login .content {
    padding: 20px;
}

.login .content h1 {
    font-size: 24px;
    text-align: center;
    margin-bottom: 20px;
}

.login .content {
    background: #fff;
    border-radius: 6px;
    box-shadow: 5px 5px 20px rgba(0, 0, 0, 0.1);
}
</style>